package com.classic.okhttp.gateway.http;

import com.classic.okhttp.base.OkHttpUtils;
import com.classic.okhttp.base.callback.StringCallback;
import com.google.gson.Gson;

import java.lang.reflect.Type;

import org.json.JSONObject;

/**
 * 通用对象解析
 * <pre>使用Gson进行解析</pre>
 *
 * @author 续写经典
 * @date 2015/12/18
 */


public abstract class ObjectCallback<T> extends StringCallback {

    private static final int SUCCESS_CODE = 200;
    private static final String KEY_CODE = "code";
    private static final String KEY_OBJECT = "returnObject";
    private int code = 0;

    @Override
    public void onSuccess(String json) {
        try {
            if (null == json || "".equals(json) || json.length() == 0 || json.equals("null")) {
                onError(OkHttpUtils.DEFAULT_ERROR_CODE, "");
                return;
            }
            final String content;
            code = new JSONObject(json).getInt(KEY_CODE);
            if (new JSONObject(json).has(KEY_OBJECT)) {
                content = new JSONObject(json).getString(KEY_OBJECT);
            } else {
                if (code == 200) {
                    content = "{returnObject: 成功}";
                } else {
                    content = "{returnObject: 失败}";
                }
            }
            if (code == SUCCESS_CODE) {
                T obj = new Gson().fromJson(content, getType());
                onSuccess(obj);
            } else {
                onError(code, content);
            }
        } catch (Exception e) {
            if (code != 0) {
                onError(code, "");
            } else {
                onError(OkHttpUtils.DEFAULT_ERROR_CODE, "");
            }
            e.printStackTrace();
        }
    }

    public abstract void onSuccess(T response);

    /**
     * 设置要转换的对象类型  <br />
     * <pre>
     * 示例：
     * Type type = new TypeToken&lt;T&gt;(){}.getType()
     * </pre>
     */
    public abstract Type getType();
}
